"""
Author : Mr.Sun
DateTime : 2022/10/17.09:27
FileName : KeyWordsOperate.py
Desc :   关键词的操作
[
{keyword:"",
priority:""
}
]
"""

from core.OperateSqlite import sqliteOperate
from utils.logger import logger


class KeyWordsOperate(object):
    def __init__(self):
        self.sql = "select key_word, priority from key_words where status=1; "
        self.type_sql = 'select key_word from key_words where status=1 and priority=-1;'
        response = sqliteOperate().search_data(self.sql)
        self.key_words = [{"keyword": temp[0], "priority": temp[1]} for temp in response]

    def title_keys_match(self, title):
        try:
            priority_key_1 = []
            priority_key_2 = []
            for i in self.key_words:
                if i['priority'] == 1:
                    priority_key_1.append(i['keyword'])
                if i['priority'] == 2:
                    priority_key_2.append(i['keyword'])
            key = ''
            for key_1_temp in priority_key_1:
                if key_1_temp in title:
                    key = key_1_temp
                    break
                for key_2_temp in priority_key_2:
                    if key_2_temp in title and key_1_temp not in title:
                        key = key_2_temp
            if key:
                logger.info(title + " matched key is " + key)
            else:
                logger.info(title + " not match any key.")
            return key
        except Exception as e:
            logger.error("title_keys_match occur error is :" + str(e))

    def exam_type_match(self, title):
        try:
            response = sqliteOperate().search_data(self.type_sql)
            result = [temp[0] for temp in response]
            for temp in result:
                if temp in title:
                    logger.info("exam_type not match ,return .")
                    return False
                else:
                    logger.info("exam_type not match")
                    return True
        except Exception as e:
            logger.error('exam_type_match occur error is ' + str(e))
